package com.shr25.robot.qq.plugins;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.shr25.robot.common.RobotMsgPermission;
import com.shr25.robot.common.RobotMsgType;
import com.shr25.robot.qq.conf.QqConfig;
import com.shr25.robot.qq.model.QqGroupInfo;
import com.shr25.robot.qq.model.QqMessage;
import com.shr25.robot.qq.service.qqGroup.IQqGroupInfoService;
import com.shr25.robot.qq.service.qqGroup.IQqGroupLogService;
import com.shr25.robot.qq.util.MessageUtil;
import kotlin.io.FilesKt;
import net.mamoe.mirai.contact.*;
import net.mamoe.mirai.event.events.MemberJoinEvent;
import net.mamoe.mirai.event.events.MemberLeaveEvent;
import net.mamoe.mirai.event.events.MessageRecallEvent;
import net.mamoe.mirai.message.code.MiraiCode;
import net.mamoe.mirai.message.data.*;
import net.mamoe.mirai.utils.BotConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 群管理插件
 *
 * @author huobing
 * @date 2022/6/3 21:25
 */
@Component
public class GroupManageRobotPlugin extends RobotPlugin {
    @Autowired
    IQqGroupLogService qqGroupLogService;
    @Autowired
    IQqGroupInfoService qqGroupInfoService;

    /**
     * 迎新消息是否at新入群群员
     */
    @Value("${qq.manager.welcome.isAt:true}")
    private Boolean isAt;

    /**
     * 每几人加入算一轮，发送一次欢迎词
     */
    @Value("${qq.manager.welcome.avg:10}")
    private Integer avg;

    /**
     * 随机设定一轮中第几个发送欢迎词
     */
    private ConcurrentHashMap<Long, Integer> welcomeConf = new ConcurrentHashMap<>();

    /**
     * 记录第几个入群
     */
    private ConcurrentHashMap<Long, Integer> inGroupCache = new ConcurrentHashMap<>();

    /**
     * 一条消息中连续At的最大数
     */
    @Value("${qq.manager.at.count:8}")
    private Integer maxAtCount;

    /**
     * 迎新图片
     */
    private File welcomeImgDir;

    public GroupManageRobotPlugin() {
        super("群管理插件");
        addDesc("群管理,记录群员进出情况");
        addCommand("禁言", "禁言", qqMessage -> {
            Integer time = 0;
            try {
                String content = qqMessage.getContent();
                time = Integer.parseInt(content.substring(0, content.length() - 1));
                String type = content.substring(content.length() - 1);
                switch (type) {
                    case "m":
                        time = time * 60;
                        break;
                    case "h":
                        time = time * 60 * 60;
                        break;
                    case "d":
                        time = time * 60 * 60 * 24;
                        break;
                    default:
                        break;
                }
                if(time > 0) {
                    time  =  time > 30 * 60 * 60 * 24 - 60 ? 30 * 60 * 60 * 24 - 60 : time;
                    Integer finalTime = time;
                    qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                        // 过滤艾特消息
                        if (singleMessage instanceof At) {
                            Long qq = ((At) singleMessage).getTarget();
                            NormalMember user = MessageUtil.getGroupMember(qqMessage.getGroup(), qq);
                            if (user != null) {
                                if (user.isMuted()) {
                                    user.unmute();
                                }
                                user.mute(finalTime);
                            }
                        }
                    });
                }

            }catch (PermissionDeniedException e){
                qqMessage.putReplyMessage("权限不足！~~~");
            }catch (Exception e){

            }
            return true;
        });
        addCommand("解除禁言", "解除禁言", qqMessage -> {
            try{
                qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                    // 过滤艾特消息
                    if (singleMessage instanceof At) {
                        Long qq = ((At) singleMessage).getTarget();
                        NormalMember user = MessageUtil.getGroupMember(qqMessage.getGroup(), qq);
                        if (user != null && user.isMuted()) {
                            user.unmute();
                        }
                    }
                });
            }catch (PermissionDeniedException e){
                qqMessage.putReplyMessage("权限不足！~~~");
            }catch (Exception e){

            }
            return true;
        });
        addCommand("踢人", "开启新用户进群迎新消息", qqMessage -> {
            try {
                qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                    // 过滤艾特消息
                    if (singleMessage instanceof At) {
                        Long qq = ((At) singleMessage).getTarget();
                        NormalMember user = MessageUtil.getGroupMember(qqMessage.getGroup(), qq);
                        if (user != null) {
                            user.kick("");
                        }
                    }
                });
            }catch (PermissionDeniedException e){
                qqMessage.putReplyMessage("权限不足！~~~");
            }catch (Exception e){

            }
            return true;
        });
        addCommand("永久踢人", "开启新用户进群迎新消息", qqMessage -> {
            try {
                qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                    // 过滤艾特消息
                    if (singleMessage instanceof At) {
                        Long qq = ((At) singleMessage).getTarget();
                        NormalMember user = MessageUtil.getGroupMember(qqMessage.getGroup(), qq);
                        if (user != null) {
                            user.kick("", true);
                        }
                    }
                });
            }catch (PermissionDeniedException e){
                qqMessage.putReplyMessage("权限不足！~~~");
            }catch (Exception e){

            }
            return true;
        });
        addCommand("设置头衔", "设置专有头衔", RobotMsgPermission.ADMIN, new RobotMsgType[]{RobotMsgType.GroupAtBot, RobotMsgType.Group}, qqMessage -> {
            try {
                String content = qqMessage.getContent();
                qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                    // 过滤艾特消息
                    if (singleMessage instanceof At) {
                        Long qq = ((At) singleMessage).getTarget();
                        NormalMember user = MessageUtil.getGroupMember(qqMessage.getGroup(), qq);
                        if (user != null) {
                            user.setSpecialTitle(content);
                        }
                    }
                });
            }catch (PermissionDeniedException e){
                qqMessage.putReplyMessage("权限不足！~~~");
            }catch (Exception e){

            }
            return true;
        });
        addCommand("取消头衔", "取消专有头衔", RobotMsgPermission.ADMIN, new RobotMsgType[]{RobotMsgType.GroupAtBot, RobotMsgType.Group}, qqMessage -> {
            try {
                qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                    // 过滤艾特消息
                    if (singleMessage instanceof At) {
                        Long qq = ((At) singleMessage).getTarget();
                        NormalMember user = MessageUtil.getGroupMember(qqMessage.getGroup(), qq);
                        if (user != null) {
                            user.setSpecialTitle("");
                        }
                    }
                });
            }catch (PermissionDeniedException e){
                qqMessage.putReplyMessage("权限不足！~~~");
            }catch (Exception e){

            }
            return true;
        });
        addCommand("设置管理员", "设置管理员", RobotMsgPermission.ADMIN, new RobotMsgType[]{RobotMsgType.GroupAtBot, RobotMsgType.Group}, qqMessage -> {
            try {
                String content = qqMessage.getContent();
                qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                    // 过滤艾特消息
                    if (singleMessage instanceof At) {
                        Long qq = ((At) singleMessage).getTarget();
                        NormalMember user = MessageUtil.getGroupMember(qqMessage.getGroup(), qq);
                        if (user != null) {
                            user.modifyAdmin(true);
                        }
                    }
                });
            }catch (PermissionDeniedException e){
                qqMessage.putReplyMessage("权限不足！~~~");
            }catch (Exception e){

            }
            return true;
        });
        addCommand("取消管理员", "取消管理员", RobotMsgPermission.ADMIN, new RobotMsgType[]{RobotMsgType.GroupAtBot, RobotMsgType.Group}, qqMessage -> {
            try {

                String content = qqMessage.getContent();
                qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                    // 过滤艾特消息
                    if (singleMessage instanceof At) {
                        Long qq = ((At) singleMessage).getTarget();
                        NormalMember user = MessageUtil.getGroupMember(qqMessage.getGroup(), qq);
                        if (user != null) {
                            user.modifyAdmin(false);
                        }
                    }
                });
            }catch (PermissionDeniedException e){
                qqMessage.putReplyMessage("权限不足！~~~");
            }catch (Exception e){

            }
            return true;
        });
        addCommand("开启迎新", "开启新用户进群迎新消息", qqMessage -> {
            enabledWelcome(qqMessage);
            return true;
        },  true);
        addCommand("关闭迎新", "关闭新用户进群迎新消息", qqMessage -> {
            notEnabledWelcome(qqMessage);
            return true;
        }, true);
        addCommand("开启迎新图片", "开启新用户进群随机欢迎图片", qqMessage -> {
            enabledWelcomeImg(qqMessage);
            return true;
        });
        addCommand("关闭迎新图片", "关闭新用户进群随机欢迎图片", qqMessage -> {
            notEnabledWelcomeImg(qqMessage);
            return true;
        });
        addCommand("开启迎新信息", "开启新用户进群欢迎语", qqMessage -> {
            enabledWelcomeMsg(qqMessage);
            return true;
        });
        addCommand("关闭迎新信息", "关闭新用户进群欢迎语", qqMessage -> {
            notEnabledWelcomeMsg(qqMessage);
            return true;
        });
        addCommand("设置迎新信息", "设置新用户进群欢迎语", qqMessage -> {
            MessageChainBuilder messageChainBuilder = qqMessage.getMessage();
            setWelcome(qqMessage, MiraiCode.serializeToMiraiCode(messageChainBuilder));
            return true;
        });
        setSort(1000);
        // 媒体文件夹
        File baseMediaPath = FilesKt.resolve(BotConfiguration.getDefault().getWorkingDir(), SpringUtil.getBean(QqConfig.class).getWorkspace() + File.separator + "media" + File.separator);
        this.welcomeImgDir = FilesKt.resolve(baseMediaPath, "welcome_img");
        FileUtil.mkdir(this.welcomeImgDir);
    }


    /**
     * 开启开启迎新
     * @param qqMessage
     */
    private void enabledWelcome(QqMessage qqMessage){
        initGroup(qqMessage);
        qqGroupInfoService.update().set("is_img", 1).set("is_msg", 1).eq("group_id", qqMessage.getGroupId()).update();
        qqMessage.putReplyMessage("设置成功！~~~~");
    }

    /**
     * 关闭迎新
     * @param qqMessage
     */
    private void notEnabledWelcome(QqMessage qqMessage){
        qqGroupInfoService.update().set("is_img", 0).set("is_msg", 0).eq("group_id", qqMessage.getGroupId()).update();
        qqMessage.putReplyMessage("设置成功！~~~~");
    }

    /**
     * 开启迎新随机图片
     * @param qqMessage
     */
    private void enabledWelcomeImg(QqMessage qqMessage){
        initGroup(qqMessage);
        qqGroupInfoService.update().set("is_img", 1).eq("group_id", qqMessage.getGroupId()).update();
        qqMessage.putReplyMessage("设置成功！~~~~");
    }
    /**
     * 关闭迎新随机图片
     * @param qqMessage
     */
    private void notEnabledWelcomeImg(QqMessage qqMessage){
        qqGroupInfoService.update().set("is_img", 0).eq("group_id", qqMessage.getGroupId()).update();
        qqMessage.putReplyMessage("设置成功！~~~~");
    }

    /**
     * 开启迎新欢迎语
     * @param qqMessage
     */
    private void enabledWelcomeMsg(QqMessage qqMessage){
        initGroup(qqMessage);
        qqGroupInfoService.update().set("is_msg", 1).eq("group_id", qqMessage.getGroupId()).update();
        qqMessage.putReplyMessage("设置成功！~~~~");
    }
    /**
     * 关闭迎新欢迎语
     * @param qqMessage
     */
    private void notEnabledWelcomeMsg(QqMessage qqMessage){
        qqGroupInfoService.update().set("is_msg", 0).eq("group_id", qqMessage.getGroupId()).update();
        qqMessage.putReplyMessage("设置成功！~~~~");
    }

    /**
     * 设置迎新欢迎语
     * @param qqMessage
     * @param welcome
     */
    private void setWelcome(QqMessage qqMessage, String welcome){
        initGroup(qqMessage);
        qqGroupInfoService.update().set("is_msg", 1).set("welcome", welcome).eq("group_id", qqMessage.getGroupId()).update();
        qqMessage.putReplyMessage("设置成功！~~~~");
    }

    private void initGroup(QqMessage qqMessage){
        QqGroupInfo qqGroupInfo = qqGroupInfoService.query().eq("group_id", qqMessage.getGroupId()).one();
        if(qqGroupInfo == null){
            Group group = MessageUtil.getGroup(qqMessage.getGroupId());
            qqGroupInfo = new QqGroupInfo();
            qqGroupInfo.setGroupId(group.getId());
            qqGroupInfo.setGroupName(group.getName());
            qqGroupInfoService.save(qqGroupInfo);
        }
    }

    @Override
    public boolean executeOtherMessage(QqMessage qqMessage) {
        if(qqMessage.getEvent() instanceof MessageRecallEvent.GroupRecall){
            MessageRecallEvent.GroupRecall groupRecall = qqMessage.getMyEvent();
            if(!qqMessage.getBotId().equals(groupRecall.getOperator().getId())){
                groupRecall.getMessageIds();
                log.info("{}撤回了一条消息",groupRecall.getAuthorId());
            }
        }
        return true;
    }

    @Override
    public boolean executeGroupMessage(QqMessage qqMessage) {
        MemberPermission botPermission = qqMessage.getBotPermission();
        if(botPermission == MemberPermission.ADMINISTRATOR || botPermission == MemberPermission.OWNER){
            if(qqMessage.getRobotMsgPermission().getPermission() > 3){
                NormalMember normalMember = qqMessage.getGroup().get(qqMessage.getSenderId());
                AtomicReference<Integer> atCount = new AtomicReference<>(0);
                qqMessage.getMessageEvent().getMessage().forEach(singleMessage -> {
                    if(singleMessage instanceof MessageContent) {
                        // 过滤艾特消息
                        if (singleMessage instanceof At) {
                            atCount.getAndSet(atCount.get() + 1);
                        }
                    }
                });
                if(atCount.get()>maxAtCount){
                    MessageSource.recall(qqMessage.getMessageEvent().getMessage());
                    normalMember.mute(60);
                }
            }

        }
        return true;
    }

    @Override
    public boolean executeGroupMember(QqMessage qqMessage) {
        AtomicBoolean executeNext = new AtomicBoolean(true);
        //成员已经加入群的事件
        if (qqMessage.getEvent() instanceof MemberJoinEvent) {
            Member member = qqMessage.getGroupMemberEvent().getMember();
            if(member != null) {
                log.info("{}加入群：{}", member.getId(), qqMessage.getGroupId());
                welcome(qqMessage);
            }
        } else if (qqMessage.getEvent() instanceof MemberLeaveEvent.Kick) { //成员被踢出群. 成员不可能是机器人自己.

        } else if (qqMessage.getEvent() instanceof MemberLeaveEvent.Quit) { //成员主动离开
            out(qqMessage);
        }
        return executeNext.get();
    }

    /**
     * 欢迎语
     * @param qqMessage
     */
    private void welcome(QqMessage qqMessage){
        if(isSendWelcome(qqMessage)) {
            Member member = qqMessage.getGroupMemberEvent().getMember();
            QqGroupInfo qqGroupInfo = qqGroupInfoService.query().eq("group_id", qqMessage.getGroupId()).one();

            if (qqGroupInfo != null && (qqGroupInfo.getIsImg() == 1 || qqGroupInfo.getIsMsg() == 1)) {
                MessageChainBuilder builder = MessageUtil.createBuilder();
                log.info("欢迎需要AT群员：{}", isAt);
                if(isAt){
                    builder.append(new At(member.getId()));
                }
                if (qqGroupInfo.getIsImg() == 1) {
                    File file = MessageUtil.randomFile(this.welcomeImgDir);
                    if (file != null) {
                        if (file != null) {
                            builder.append(MessageUtil.buildImageMessage(qqMessage.getContact(), file));
                        }
                    }
                }
                if (qqGroupInfo.getIsMsg() == 1 && StringUtils.isNotBlank(qqGroupInfo.getWelcome())) {
                    MessageChain messageChain = MiraiCode.deserializeMiraiCode(qqGroupInfo.getWelcome());
                    builder.addAll(messageChain);
                }
                qqMessage.putReplyMessage(qqMessage.getContact(), builder.build());
            }
        }
    }

    /**
     * 是否随机发送欢迎词
     * @param qqMessage
     * @return
     */
    private boolean isSendWelcome(QqMessage qqMessage){
        Random random = new Random();
        Integer randomInt = random.nextInt(avg);
        Boolean flag = false;
        synchronized (qqMessage.getGroupId()){
           Integer conf = welcomeConf.get(qqMessage.getGroupId());
           if(conf == null || conf > avg){
               conf = randomInt.intValue();
               welcomeConf.put(qqMessage.getGroupId(), conf);
           }
            //本轮第几个入群
            Integer index = inGroupCache.get(qqMessage.getGroupId());
           if(index == null){
               index = 1;
           }else{
               index = (index+1)%avg;
           }
            log.info("欢迎随机数：{}，本轮第几次：{}", conf, index);
            if(conf == index){
                flag = true;
            }
            inGroupCache.put(qqMessage.getGroupId(), index);
           //如果是一轮的最后一次，则重新计算随机数
           if(index == 0){
               conf = randomInt.intValue();
               welcomeConf.put(qqMessage.getGroupId(), conf);
           }
        }

        return flag;
    }

    /**
     * 退出发送提醒
     * @param qqMessage
     */
    private void out(QqMessage qqMessage){
        QqGroupInfo qqGroupInfo = qqGroupInfoService.query().eq("group_id", qqMessage.getGroupId()).one();
        if(qqGroupInfo != null && qqGroupInfo.getIsOutMessage() == 1) {
            // 发一条消息到群里
            MemberLeaveEvent.Quit event = qqMessage.getQuitMemberLeaveEvent();
            // 构建链式消息
            At at = new At(event.getGroup().getOwner().getId());
            MessageChainBuilder messageChainBuilder = new MessageChainBuilder();
            messageChainBuilder.append(at);
            messageChainBuilder.append(String.format("\n有人离开了：%s(%s)", event.getMember().getNick(), event.getMember().getId()));
            qqMessage.putReplyMessage(event.getGroup(), messageChainBuilder);
        }
    }
}
